<template>
  <el-form
    :model="item"
    ref="itemForm"
    :rules="rules"
    label-width="120px"
    class="cate-container"
  >
    <el-form-item label="商品名" prop="itemName">
      <el-input v-model="item.itemName" />
    </el-form-item>
    <el-form-item label="价格" prop="itemPrice">
      <el-input-number :min="0" v-model="item.itemPrice" />
    </el-form-item>
    <el-form-item label="上下架" prop="itemStatus">
      <el-switch
        v-model="item.itemStatus"
        :active-value="0"
        :inactive-value="1"
        inline-prompt
        active-text="上架"
        inactive-text="下架"
      />
    </el-form-item>
    <el-form-item label="所属分类" prop="cateId">
      <el-tree-select
        v-model="item.cateId"
        check-strictly
        :data="[{ id: -1, cateName: '请选择一个分类' }, ...cates]"
        :props="{ label: 'cateName', value: 'id' }"
      />
    </el-form-item>
    <el-form-item label="商品描述" prop="itemDesc">
      <el-input v-model="item.itemDesc" type="textarea" />
    </el-form-item>
    <el-form-item label="商品图片">
      <el-upload
        v-model:file-list="fileList"
        accept=".jpg,.jpeg,.png,.gif"
        class="upload-demo"
        action="/api/upload"
        list-type="picture-card"
        multiple
        :on-remove="handleRemove"
        :on-success="handleUploadSuccess"
        :limit="3"
      >
        <el-button type="primary">点击上传</el-button>
        <template #tip>
          <div class="el-upload__tip">第一张图自动作为商品封面</div>
        </template>
      </el-upload>
    </el-form-item>
    <el-form-item label="商品详情">
      <div style="border: 1px solid #ccc">
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editor"
          :defaultConfig="toolbarConfig"
          mode="default"
        />
        <Editor
          style="height: 500px; overflow-y: hidden"
          v-model="item.content"
          :defaultConfig="editorConfig"
          mode="default"
          @onCreated="onCreated"
        />
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">确定</el-button>
      <el-button>重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getCateLists } from "@a/cate";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { addItem } from "@/api/item";
import "@wangeditor/editor/dist/css/style.css";
export default {
  name: "ItemAdd",
  data() {
    return {
      rules: {
        itemName: [
          {
            required: true,
            message: "请输入商品名称",
          },
        ],
      },
      // 富文本相关
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {
          uploadImage: {
            server: "/api/upload",
            customInsert: (res, insertFn) => {
              // 触发回调  insertFn(url, alt, href)
              if (res.code === 200) {
                insertFn(res.data.url);
              }
            },
          },
        },
      },
      item: {
        itemName: "",
        itemPrice: 0,
        itemDesc: "",
        imgs: [],
        itemStatus: 0, // 0上架 1 下架
        cateId: -1,
        content: "", //商品详情
      },
      cates: [],
      fileList: [],
    };
  },

  methods: {
    onSubmit() {
      this.$refs.itemForm
        .validate()
        .then(() => {
          addItem(this.item).then((res) => {
            if (res.data.code === 200) {
              this.$message({
                type: "success",
                message: "添加成功",
                duration: 1500,
                onClose: () => {
                  // 回到列表
                  this.$router.replace("/itemLists");
                },
              });
            }
          });
        })
        .catch(() => {
          this.$message.error("请填写完整信息");
        });
    },
    // 富文本初始化完成事件
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    handleRemove(file) {
      // 点击删除 图片， 删除 待上传的 imgs 对应图片
      console.log(file);
      const delIndex = this.item.imgs.findIndex(
        (item) => item === file.response.data.url
      );
      this.item.imgs.splice(delIndex, 1);
      // 请求 把服务器中 对应 文件也要删除
    },
    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.item.imgs.push(res.data.url);
      }
    },
    getCateLists() {
      getCateLists().then((res) => {
        if (res.data.code === 200) {
          this.cates = res.data.data;
        }
      });
    },
  },
  created() {
    this.getCateLists();
  },
  components: { Editor, Toolbar },
};
</script>

<style lang="scss" scoped>
.cate-container {
  max-width: 800px;
}
</style>
